package cn.smbms.controller;

import cn.smbms.pojo.User;
import cn.smbms.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Author: laoyu
 * @Date: 2019/8/28 9:44
 * @Description:
 */
@Controller
public class UserController extends BaseController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;

    /**
     * 登录验证的方法
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/dologin.html")
    public String queryForUser(HttpServletRequest request,
                               HttpSession session) {
        logger.debug("开始验证用户信息=====================");
        //用户名和密码
        String userName = request.getParameter("userName");
        String pwd = request.getParameter("password");
        //调用service
        User user = userService.queryUserByCondition(userName, pwd);
        //判断用户对象是否为空
        if (null != user) {
            //如果用户不为空，则转发到admin.jsp
            logger.debug("通过验证=====================");
            //携带用户信息
            session.setAttribute("user", user);
            return "forward:/userlist.html";
        } else {
            //如果用户为空，重定向到index.jsp
            logger.debug("用户不合法，请重新登录=====================");
            session.setAttribute("error", "用户名或密码错误！");
            return "redirect:/index.jsp";
           /* //抛异常
            throw new RuntimeException("用户名或密码错误");*/
        }
    }

    //捕获局部异常的方法
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException e,
                                   HttpServletRequest request) {
        request.setAttribute("e", e.getMessage());
        return "error";
    }

    /**
     * 跳转到admin.jsp
     *
     * @return
     */
    @RequestMapping(value = "/admin.html")
    public String toAdmin(HttpSession session) {
        //从session中获取用户记录
        if (null != session.getAttribute("user")) {
            //返回admin.jsp
            return "admin";
        } else {
            return "index";
        }
    }

    /**
     * 跳转到首页
     *
     * @return
     */
    @RequestMapping(value = "/index.html")
    public String toLogin() {
        //返回index.jsp
        return "index";
    }

    @RequestMapping(value = "/userlist.html")
    public String getUserList(Model model) {
        //调用service层的方法，获取用户列表
        List<User> userList = userService.getUserList();
        //将用户列表添加到模型=====>>>>${userList}
        model.addAttribute("userList", userList);
        //返回视图名称
        return "userList";
    }

    @RequestMapping(value = "/edituser.do", method = RequestMethod.GET)
    public String toEditUser(@RequestParam(value = "userId") Integer userId,
                             Model model) {
        //调用service方法，根据ID获取用户信息
        User user = userService.queryUserById(userId);
        //将User对象添加到模型中，在编辑用户信息后覆盖这个对象
        model.addAttribute("user", user);
        return "editUser";
    }

    @RequestMapping(value = "/userupdate.html")
    public String modifyUserSave(User user
            , HttpSession session) {
        System.out.println("=============================\n\n" + user.toString());
        //更新标记
        user.setModifyDate(new Date());
        user.setModifyBy(((User) session.getAttribute("user")).getId());
        //更新
        if (userService.modifyUserById(user)) {
            //更新成功，跳转到用户列表
            return "redirect:/userlist.html";
        }
        return "editUser";
    }


    @RequestMapping(value = "/userlist1.html")
    public String queryUserByNameAndRole(@RequestParam(value = "userName", required = false)
                                                 String queryUserName,
                                         @RequestParam(value = "userRole", required = false)
                                                 String queryUserRole,
                                         Model model) {
        //调用service层方法查询用户
        if (queryUserName == null || queryUserName.equals("")) {
            queryUserName = null;
        }
        String _queryRole = "0";
        if (queryUserRole != null && !queryUserRole.equals("0")) {
            _queryRole = queryUserRole;
        } else {
            _queryRole = null;
        }
        System.out.println("==========" + queryUserName + "-->" + _queryRole + "\n\n");
        List<User> userList = userService.queryUserByNameAndRole(queryUserName, _queryRole);
        model.addAttribute("userList", userList);
        return "userList";
    }


    /**
     * 添加新用户
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    public String toAddUser(Model model, User user) {
        model.addAttribute("user", user);
        return "addUser";
    }

    @RequestMapping(value = "/usersave.html", method = RequestMethod.GET)
    public String addUserSave(User user, HttpSession session) {
        //其他记录信息
        user.setCreatedBy(((User) session.getAttribute("user")).getId());
        user.setCreationDate(new Date());

        //调用service方法，添加新用户
        boolean b = userService.addNewUser(user);
        //如果添加成功，重定向到/userlist.html
        if (b) {
            return "redirect:/userlist.html";
        }
        System.out.println(user.toString());
        //添加失败，仍然停留在添加页面
        return "addUser";
    }

    @RequestMapping(value = "/del.html/{id}")
    public String deleteById(@PathVariable Integer id) {
        logger.debug("id:============================a" + id);
        if (userService.deleteById(id)) {
            //删除成功
            logger.debug("id:" + id + "==================用户删除成功！\n");
        }
        return "redirect:/userlist1.html";
    }
}
